package com.zxb.base.system;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zxb.core.common.R;
import com.zxb.core.common.service.MinioService;
import com.zxb.core.dao.system.SysAttach;
import com.zxb.core.dao.system.SysAttachDao;
import com.zxb.core.util.JsonUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.poi.util.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class FileController {

    private final MinioService minioService;
    private final SysAttachDao attachDao;

    @PostMapping("/file/upload")
    public R<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
        String name = file.getName();
        Long size = file.getSize();
        String path = minioService.upload(file);
        ObjectNode on = JsonUtil.on();
        on.put("name",name);
        on.put("size",size);
        on.put("path",path);
        return R.success(on);
    }

    @PostMapping("/file/remove")
    public R<?> upload(@RequestBody Map<String,String> map) {
        minioService.del(map.get("path"));
        return R.success();
    }

    @GetMapping("/file/download")
    @ApiOperation("附件下载")
    public ResponseEntity<byte[]> download(Long id) throws IOException {
        SysAttach attach = attachDao.getById(id);
        if (null == attach) {
            return null;
        }
        String filePath = attach.getFilePath();
        String HTTP = "http";
        if (filePath.contains(HTTP)) {
            int startIndex = filePath.indexOf("/upload/");
            filePath = filePath.substring(startIndex);
        }
        InputStream is = minioService.getObject(filePath);
        byte[] fileByteArray = IOUtils.toByteArray(is);

        HttpHeaders headers = new HttpHeaders();

        String downloadFileName = new String(attach.getFileName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentLength(fileByteArray.length);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileByteArray);
    }
}
